
/*
* List of globals
*/
var globalFlags = {validationFlag: false};
var myListingContainer = new Array();
var friendsListingContainer = new Array();
var listing = {subject: '', description: ''};
var friendsListing = {subject: '', description: '', name:'', id:''};
var mini;
var tabSet;
var message = new Array();
var globalFriends = new Array();
var me = {};
var isOwnerViewer = false;
var validationMessage;
function init() {
  formatUI();
  onLoadFreinds();
}



function createTab(tabName){
    mini = new gadgets.MiniMessage(); 
    tabSet = new gadgets.TabSet(null, null, document.getElementById("tabContainer"));
    
    var o = tabSet.addTab(tabName+ "'s Listing", { 
                             contentContainer: _gel("yourListinConatiner"),
                             tooltip: "My Tab" 
                        }); 
    var friendsTab = tabSet.addTab("Friends Listing", { 
                             contentContainer: _gel("friendsContainer"),
                             tooltip: "Firends Tab" 
                        }); 
    tabSet.alignTabs('left');
}

function createIframe(){
   
   ifrm = document.createElement("IFRAME");
   ifrm.setAttribute("src", "http://google.com/");
   ifrm.style.width = 640+"px";
   ifrm.style.height = 480+"px";
   document.getElementById("Iframe").appendChild(ifrm);
 
}

function formatUI(){
     //do some cosmetics work
    $('#createNewListing').slideUp();     
    $('#toggle').click(function(){
        $('#createNewListing').slideDown();
    });
   /* $('#descriptionSubmit').click(function(){
        $('#createNewListing').slideUp();     
    });*/
    $('#descriptionSubmit').click(function(){
        submitNewListing();
    });
    
    $('#descriptionCancel').click(function(){
       $('#createNewListing').slideUp();  
    });
 
 
}

function onLoadFreinds(){
    //call yourself, your friends and app data to get the data
     var req = opensocial.newDataRequest();
     var opt_params = {};
     opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
                                        opensocial.Person.Field.NAME,
                                        opensocial.Person.Field.GENDER,
                                        opensocial.Person.Field.PROFILE_URL,
                                        opensocial.Person.Field.THUMBNAIL_URL];
										
	 opt_params[opensocial.DataRequest.PeopleRequestFields.FILTER] = opensocial.DataRequest.FilterType.HAS_APP; 
	 opt_params[opensocial.DataRequest.PeopleRequestFields.MAX] = 240; 
     req.add(req.newFetchPersonRequest("OWNER", opt_params), "viewer");
     req.add(req.newFetchPeopleRequest(opensocial.DataRequest.Group.OWNER_FRIENDS, opt_params), 'viewerFriends');
     
    
     var fields = ["Listing"];
    // req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER), "viewer");
    req.add(req.newFetchPersonAppDataRequest("OWNER", fields), "viewer_data");
    req.add(req.newFetchPersonAppDataRequest('OWNER_FRIENDS', fields), 'viewerFriendData');
    req.send(responseOnLoad);
}

/*
*This is for testing purposes only 
*/
function clearOutData(){
    var req = opensocial.newDataRequest();
    req.add(req.newUpdatePersonAppDataRequest("OWNER", "Listing", ''));
    req.send(clearNotification);
}

function clearNotification(data){
    if(!data.hadError()){
        alert("Data Cleared");
    }
}

//testing code ends
function responseOnLoad(data){
    if(data.hadError()){
        alert("There was a problem communicating with the server, please try again later");
    }else{
                
            //show your name next to the greeting
            var viewer = data.get("viewer").getData();
            me = data.get("viewer").getData();
            createTab(me.getDisplayName());
            isOwnerViewer = me.isViewer();
            
            if(!isOwnerViewer){
                document.getElementById('newListingContainer').style.display = 'none';
            }
            var viewerFriends = data.get('viewerFriends').getData();
            var viewerFriendsData = data.get('viewerFriendData').getData();
           /* var name = viewer.getDisplayName();
            document.getElementById('viewer_name').innerHTML = name;
            */
            //show my listings
          //  var x = data.get("viewer_data").getData()[viewer.getId()]["Listing"];
            
            if(typeof(data.get("viewer_data").getData()[viewer.getId()]) != 'undefined'){
                var appData = data.get("viewer_data").getData()[viewer.getId()]["Listing"];
                populateOwnListing(appData);
            }
                             
            //show my friends listing
            populateFriendsListing(viewerFriends, viewerFriendsData);
            
    }
}

function populateFriendsListing(friends, data){
	
   
   for(var id in data){
		
		var personData = data[id];
		if(personData){
			var json = data[id]['Listing'];
			var frListing = {};
			
			try{
				frListing = gadgets.json.parse(gadgets.util.unescapeString(json));
			}catch(e){
				frListing = {};
			}
			globalFriends[id] = friends.getById(id);
			friendsListingContainer[id] = frListing;
		} 
	}

   /*friends.each(function(person){
        var personData = data[person.getId()];
       if(personData){
            var json = data[person.getId()]['Listing'];
            var frListing = {};
            if(!json){
                frListing ={};
            }
            try {
                frListing = gadgets.json.parse(gadgets.util.unescapeString(json));
              } catch (e) {
                frListing = {};
            }
            globalFriends[person.getId()] = person;
            friendsListingContainer[person.getId()] = frListing;
		}
    });*/
	
				
    
    showFriensListing();  
}

function response(data) {
    if(data.hadError()){
        alert("There was a problem communicating with the server, please try again later");
    }else{
                
            //show your name next to the greeting
            var viewer = data.get("viewer").getData();
           // var viewerFriends = data.get('viewerFriends').getData();
           // var name = viewer.getDisplayName();
           // document.getElementById('viewer_name').innerHTML = name;
            
            //Show my listings
            //get your own app data and display it
            
            var appData = data.get("viewer_data").getData()[viewer.getId()]["Listing"];
            populateOwnListing(appData);
           
     }   
}

function populateOwnListing(appData){
     var unescapedString = gadgets.util.unescapeString(appData); 
     var obj = gadgets.json.parse(unescapedString); 
     myListingContainer.length = 0;
  
     jQuery.each(obj, function(i, val){myListingContainer.push(val)});
   
     showListing();
      
       var x = document.getElementById("processingDivContent");
      if(x!=null){
          var html = document.getElementById("processingDivContent").innerHTML;
          html += "<br/> Updating UI";
          x.innerHTML = html;
      }
}

function submitNewListing(){
      listing.subject = document.getElementById('subject').value;
      listing.description = document.getElementById('description').value;
      
      if((listing.subject != "") && (listing.description !="")){
          dismissValidationMessage();
          $('#createNewListing').slideUp();    
          document.getElementById("processingDiv").style.display = "";
          
          var html = "Processing.... <br/> Contacting Google Server";
          var x = document.getElementById("processingDivContent")
          if(x!=null){
            x.innerHTML = html;
          }
          myListingContainer.push(listing);
          sendData();
          
          postActivity();
		  //post the event on google analytics
		  pageTracker._trackEvent("submission", "Listing submitted", "submit", 1);
		  
      }else{
      
         if(!globalFlags.validationFlag){
                createValidationMessage();
         }
      }
    
}

//this is just for updating the viewer's request and listing, call onload friends to update friends listing
function sendData(){
      var req = opensocial.newDataRequest();     
      var json = gadgets.json.stringify(myListingContainer);
      req.add(req.newUpdatePersonAppDataRequest("VIEWER", "Listing", json));
      var opt_params = {};
      opt_params[opensocial.DataRequest.PeopleRequestFields.PROFILE_DETAILS] = [
                                        opensocial.Person.Field.NAME,
                                        opensocial.Person.Field.GENDER,
                                        opensocial.Person.Field.PROFILE_URL,
                                        opensocial.Person.Field.THUMBNAIL_URL]; 
      var fields = ["Listing"];
      req.add(req.newFetchPersonRequest("OWNER", opt_params), "viewer");
      req.add(req.newFetchPersonAppDataRequest("OWNER", fields), "viewer_data");
      req.add(req.newFetchPeopleRequest('OWNER_FRIENDS', opt_params), 'viewerFriends');
      req.send(response);
}

function showListing(data){
//remove all the existing children for the  tbody
        
        //first remove the existing table body
        var body = document.getElementById('tBody');
        if(body){
            document.getElementById("ownListingTable").removeChild(body);
        }
        var flag = false;
       var tBody = document.createElement("tbody");
        tBody.id = "tBody";
        for(var i=0; i<myListingContainer.length; i++){
            flag = true;
            var tr = document.createElement("tr");
            tr.id = "row_"+i;
            
           jQuery.each(myListingContainer[i], function(i, val){
                var subject = document.createElement("td");
                subject.appendChild(document.createTextNode(val));
                tr.appendChild(subject);
           })            
            
            if(isOwnerViewer){
                var remove = document.createElement("td");
                var link = document.createElement("a");
                link.href = "javascript:void(0);"
                link.id = "removelink_" +i;
                link.innerHTML ="remove";
                remove.appendChild(link);
                tr.appendChild(remove);
            }
            
            tBody.appendChild(tr);    
            document.getElementById("ownListingTable").appendChild(tBody);
        }
        
        assignHandlers();
        var x = document.getElementById("processingDiv");
        if(x!=null){
            setTimeout(function(){
                //hide the message
               document.getElementById("processingDiv").style.display = "none";
               
            }, 500);
        }    
        
        if(!flag){
            document.getElementById('replacingText').innerHTML = "Currently there are no listings"; 
            document.getElementById('yourListing').style.display = "none";
        }else{
            document.getElementById('replacingText').innerHTML = " ";
            document.getElementById('yourListing').style.display = "";
           // $('#ownListingTable').tableHover(); 
        }

}


function showFriensListing(){
    var tBody = document.createElement("tbody");
    tBody.id = "firendsTBody";
    var flag = false;
    var count = 0;
  
    for(var key in friendsListingContainer){
        jQuery.each(friendsListingContainer[key], function(i, val){
            flag = true;
            var tr = document.createElement("tr");
            tr.id = "friendsRow_"+i;
            
            var id = document.createElement("td");
            var frnd = document.createElement("span");
            frnd.id = ''+key +"_"+ i+'';
            frnd.setAttribute("class", "jTip");
            //frnd.innerHTML = "<a href='javascript:openNewWin("+globalFriends[key].getField(opensocial.Person.Field.PROFILE_URL)+");'>"+globalFriends[key].getDisplayName()+"</a>";
            var win = document.createElement("a");
            win.innerHTML=globalFriends[key].getDisplayName();
            win.href = 'javascript:openNewWin("'+globalFriends[key].getField(opensocial.Person.Field.PROFILE_URL)+'");';
            frnd.appendChild(win);
               
            var tipContent = document.createElement("span");
            tipContent.setAttribute("class", "myContent");
            
            var con = document.createElement('span');
            con.innerHTML = '<span>Details: '+globalFriends[key].getDisplayName()+'</span> </br> <img src='+globalFriends[key].getField(opensocial.Person.Field.THUMBNAIL_URL);+'/> ';
            tipContent.appendChild(con);
            
            /*var img = document.createElement('img');
            img.src = globalFriends[key].getField(opensocial.Person.Field.THUMBNAIL_URL);
            tipContent.appendChild(img);*/
            
            tipContent.setAttribute("style", "display: none");
                       
            
            frnd.appendChild(tipContent);
            
            
            id.appendChild(frnd);
            tr.appendChild(id);
            
            jQuery.each(val, function(i, x){
                        var subject = document.createElement("td");
                        subject.appendChild(document.createTextNode(x));
                        tr.appendChild(subject);
               }); 
           
           /*var prof = document.createElement("td");
            var win = document.createElement("a");
            win.innerHTML="Visit Profile";
            win.href = "javascript:openNewWin("+ globalFriends[key].getId()+");"
            prof.appendChild(win);
            tr.appendChild(prof);
            */
            tBody.appendChild(tr); 
        
        });     
    }
    
   
    document.getElementById('friendsListingTable').appendChild(tBody);
    createTooltips();
    
    if(!flag){
        document.getElementById('friendsReplacingText').innerHTML= me.getDisplayName()+ "'s friends currently dont have any listings";
        document.getElementById('firendsListing').style.display= "none";
    }else{
        document.getElementById('friendsReplacingText').innerHTML= "";
        document.getElementById('firendsListing').style.display= "";
    }
}

function openNewWin(key){
    window.open(key);
}
function createTooltips(){
     $(".jTip").tooltip({tooltipcontentclass:"myContent",width:400});
}

function assignHandlers(){
    for(var i=0; i<myListingContainer.length; i++){
        $('#removelink_'+i).click(setRemoveLink(i));
    }
}

function setRemoveLink(id){
    return function(){createMessageToRemove(id); }
}

function removeLink(id){
    //get the row id and remove it
    document.getElementById('tBody').removeChild(document.getElementById('row_'+id));
    //remove it from the json object
    myListingContainer.splice(id, 1);
    //make a request and update the UI
    sendData();
    dismissMessage(id);
}

function createMessageToRemove(id){
    var html = "<p>Are you sure you want to remove the listing? </p> <br/>  <input type='button' value='ok' onclick='removeLink("+id+")' /> <input type='button' value='cancel' onclick='dismissMessage("+id+")' />";
    message[id] = mini.createStaticMessage(html);
}

function dismissMessage(id){
    mini.dismissMessage(message[id]);    
}

function createValidationMessage(){
    var html="fields marked * are required. Please fill out the required fields and click submit";
    validationMessage = mini.createStaticMessage(html);
    globalFlags.validationFlag = true;
}

function dismissValidationMessage(){
    mini.dismissMessage(validationMessage);
    globalFlags.validationFlag = false;
}

function postActivity(){
      var buysell = document.getElementById('DropDownList1').value;
      
      var title = " wants to "+buysell+" "+ myListingContainer[myListingContainer.length -1].subject;
      
      var params = {};
      params[opensocial.Activity.Field.TITLE] = title;
      var activity = opensocial.newActivity(params);
      opensocial.requestCreateActivity(activity, opensocial.CreateActivityPriority.HIGH, function() {});
      
      //send message to all your friends saying stuff
      
      var message = opensocial.newMessage(myListingContainer[myListingContainer.length -1].descrption);
      message.setField('TITLE', title);
      
      
      
      //I get Not implemented error
      /*var permission = opensocial.Permission;
     
      opensocial.requestPermission(permission, "Just like that", shareThisApp)
      opensocial.requestSendMessage('VIEWER_FRIENDS', message, shareThisApp);
      
      opensocial.requestShareApp('VIEWER_FRIENDS', null, shareThisApp)
      */
}

function shareThisApp(data){
    
}

function profileInit(){
      var req = opensocial.newDataRequest();
     req.add(req.newFetchPersonRequest("OWNER"), "viewer");

     var fields = ["Listing"];
     req.add(req.newFetchPersonRequest(opensocial.DataRequest.PersonId.OWNER), "viewer");
     req.add(req.newFetchPersonAppDataRequest("OWNER", fields), "viewer_data");
     req.send(profileViewOnLoad);
     mini = new gadgets.MiniMessage();
}

function profileViewOnLoad(data){
    if(data.hadError()){
        alert("There was a problem communicating with the server, please try again later");
    }else{
                
            //show your name next to the greeting
            var viewer = data.get("viewer").getData();
            me = data.get("viewer").getData();
            isOwnerViewer = me.isViewer();
            
            document.getElementById("ownerInfo").innerHTML=me.getDisplayName() +"'s Listing: </br>";;
            
            if(typeof(data.get("viewer_data").getData()[viewer.getId()]) != 'undefined'){
                var appData = data.get("viewer_data").getData()[viewer.getId()]["Listing"];
                populateOwnListing(appData);
            }
    }
}